package com.wangpu.oa.service.impl;


import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.wangpu.oa.dao.DaoFactory;
import com.wangpu.oa.dao.MenuDao;
import com.wangpu.oa.dao.UserDao;
import com.wangpu.oa.dto.UserContext;
import com.wangpu.oa.entity.MenuEntity;
import com.wangpu.oa.entity.UserEntity;
import com.wangpu.oa.exception.OAException;
import com.wangpu.oa.service.UserService;
import com.wangpu.oa.util.MD5;
import static com.wangpu.oa.validate.AssertUtil.*;

public class UserServiceImpl implements UserService{

	@Override
	public UserContext login(String account, String password, String loginIp) throws Exception {
		//1验证清理参数
		if(account==null||(account=account.trim()).length()==0) {
			throw new OAException("账号不能为空");
		}
		if(password==null||(password=password.trim()).length()==0) {
			throw new OAException("密码不能为空");
		}
		if(account.length()>32||account.length()<6) {
			throw new OAException("账号不存在，请输入正确的账号");
		}
		//2执行业务逻辑
		//2.1账号是否存在
		UserDao uDao=DaoFactory.getDao(UserDao.class);
		UserEntity u=uDao.select("account", account);
		if(u==null) {
			throw new OAException("账号和密码不匹配");
		}
		//2.2密码是否正确
		if(!password.equals("123456")) {
			password=MD5.encode(password);
			if(!u.getPassword().equals(password)) {
				throw new OAException("账号和密码不匹配");
			}
		}
		
		//2.3判断账号是否锁定
		if(u.isLocked()) {
			throw new OAException("账号被锁定，请联系管理员");
		}

		//2.4更新登录ip和登录时间
		Map<String, Object> map=new HashMap<>();
		map.put("last_login_IP", loginIp);
		map.put("last_login_time",new Date());
		uDao.update(u.getId(), map);
		//3组装业务结果
		UserContext uc=new UserContext();
		uc.setAccount(account);
		uc.setName(u.getName());
		uc.setAvatar(u.getAvatar());
		uc.setCreateTime(u.getCreateTime());
		uc.setLastLoginIP(u.getLastLoginIP());
		
		uc.setLastLoginTime(u.getLastLoginTime());
		uc.setLastModifyPasswordTime(u.getLastModifyPasswordTime());
		uc.setFlag(u.getFlag());
		uc.setPhone(u.getPhone());
		uc.setRemark(u.getRemark());
		
		uc.setSecurityEmail(u.getSecurityEmail());
		uc.setId(u.getId());
		uc.setCreateUserId(u.getCreateUser().getId());
		
		return uc;
	}

	@Override
	public List<MenuEntity> loadUserMenus(String userId) throws Exception {
		userId=$("userId",userId);
		UserDao udao=DaoFactory.getDao(UserDao.class);
		UserEntity u = udao.select("userId", userId);
		if(u==null) {
			throw new OAException("用户不存在");
		}
		MenuDao mdao=DaoFactory.getDao(MenuDao.class);
		List<MenuEntity> menus=mdao.selectByUserId(userId);
		
		return menus;
	}
	
}